import http from 'wechat-http'

http.baseURL = 'https://live-api.itheima.net'

http.intercept.request = function (options) {
  const { token } = getApp()
  if (!options.header) {
    options.header = {
      Authorization: `Bearer ${token}`
    }
  }

  return options
}

http.intercept.response = async function ({ data, config }) {
  if (data.code === 401) {
    if (config.url.includes('/refreshToken')) {
      const router = getCurrentPages().pop()
      return wx.redirectTo({
        url: '/pages/login/index?redirectURL=/' + router
      })
    }
    const app = getApp()
    const {
      code,
      data: { token, refreshToken }
    } = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: 'Bearer ' + app.refreshToken
      }
    })
    if (code !== 10000) return wx.utils.toast()
    app.setToken('token', token)
    console.log(token)
    app.setToken('refreshToken', refreshToken)
    config = Object.assign(config, { header: { Authorization: 'Bearer ' + token } })
    return http(config)
  }
  if (data.code !== 10000) return wx.utils.toast(data.message)
  return data
}

wx.http = http

export default http
